package com.mfs.proxy.core.server.config;

import com.mfs.common.constant.Constant;
import com.mfs.proxy.core.constant.AppConstant;
import com.mfs.proxy.core.exceptions.ProxyException;
import com.mfs.proxy.core.server.registry.DefaultTimeoutProxyClientRegistry;
import lombok.Data;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Properties;

@Data
public class ServerConfig {
    private final static String NAMESPACE = Constant.MFS + "." + AppConstant.APP_NAME;
    /**
     * 代理ip，最终暴露出去给外网客户访问的，默认与服务端ip一致
     * */
    private String proxyIp;
    /**
     * 服务端ip，与代理客户端通信使用，需确保目标服务所在网络能够访问到改地址
     * */
    private String serverIp;
    /**
     * 服务端端口，与代理客户端通信使用
     * */
    private Integer serverPort;
    /**
     * 代理客户端注册中心全限定类名
     * */
    private String proxyClientRegistry;
    /**
     * 对接管理端程序
     * */
    private Boolean managerEnable;
    /**
     * 管理端地址
     * */
    private String managerUrl;

    /**
     * 用户请求超时时间，单位:分钟
     * 用户请求超过改时间未被处理，则会超时，用户通道被关闭
     * */
    private Integer requestTimeout;

    /**
     * 最大请求并发数
     * 代理请求线程池的大小，默认CPU核数
     * */
    private Integer concurrentRequestNum;


    // 单例
    private static ServerConfig instance = new ServerConfig();
    public static ServerConfig getInstance() {
        return instance;
    }
    private ServerConfig() {
        try {
            String proxyHome = System.getenv("PROXY_HOME");
            proxyHome = proxyHome.endsWith("/") ? proxyHome : proxyHome + "/";
            File file = new File(proxyHome + "server/config/server.properties");
            Properties configProperties = new Properties();
            configProperties.load(new FileInputStream(file));
            serverIp = configProperties.getProperty(NAMESPACE + ".server.ip");
            serverPort = Integer.valueOf(configProperties.getProperty(NAMESPACE + ".server.port"));
            proxyIp = configProperties.getProperty(NAMESPACE + ".server.proxy.ip", serverIp);
            proxyClientRegistry = configProperties.getProperty(NAMESPACE + "server.proxy.client.registry", DefaultTimeoutProxyClientRegistry.class.getName());
            managerEnable = Boolean.valueOf(configProperties.getProperty(NAMESPACE + ".manager.enable", "false"));
            managerUrl = configProperties.getProperty(NAMESPACE + ".manager.url");
            requestTimeout = Integer.valueOf(configProperties.getProperty(NAMESPACE + ".server.request.timeout", AppConstant.DEFAULT_REQUEST_TIMEOUT.toString()));
            concurrentRequestNum = Integer.valueOf(configProperties.getProperty(NAMESPACE + ".server.concurrent.request.num", Integer.toString(Runtime.getRuntime().availableProcessors())));
        } catch (IOException e) {
           throw new ProxyException("加载配置失败", e);
        }
    }
}
